package kernel.db.basics;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.StringTokenizer;
public class DBOperator {

	/* ############################### Fields ############################### */	/** host to the connection */
	public String host;
	/** The login for root */
	public String root;
	/** the password for user root */
	public String mdp;
	/** @see Connection */
	protected Connection con;
	/**
	 * Class constructor : initialize the url, user, and password
	 */
	public DBOperator(){
		try {
			//Register the JDBC driver for MySQL.
			Class.forName("com.mysql.jdbc.Driver");
			//Define URL of database server
			String url = "jdbc:mysql://" + host + ":3306/";
			//Get a connection to the database for root.
			con = DriverManager.getConnection(url, root, mdp);
		}
		catch (Exception e) {
		return;
		}
	}
	/**
	 * Parse the query and return a result set
	 * @param query
	 * @return
	 * @throws SQLException
	 */
	public ResultSet executeQuery(String query) throws SQLException{
		StringTokenizer st = new StringTokenizer(query);
		String mode = st.nextToken();
		if(mode.equalsIgnoreCase("SELECT")){
			return executeSelect(query);
		}else{
			if (mode.equalsIgnoreCase("INSERT") || mode.equalsIgnoreCase("UPDATE")) {
				executeUpdate(query);
			} 
			return null;
		}
	}
	/**
	 * Execute select
	 * @throws SQLException 
	 */
	public ResultSet executeSelect(String query) throws SQLException{
		return con.createStatement().executeQuery(query);
	}	
	/**
	 * Execute an update, insert, or delete
	 * @throws SQLException 
	 */
	public int executeUpdate(String query) throws SQLException{
		return con.createStatement().executeUpdate(query);
	}
}